package com.dayaokeji.rhythmschoolstudent.client.mine.group;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseActivity;
import com.dayaokeji.rhythmschoolstudent.client.home.data.bean.GroupPermission;
import com.dayaokeji.rhythmschoolstudent.client.home.meeting.ChooseParticipantsActivity;
import com.dayaokeji.rhythmschoolstudent.event.UpdateGroupEvent;
import com.dayaokeji.rhythmschoolstudent.utils.AndroidUtils;
import com.dayaokeji.rhythmschoolstudent.utils.DateUtils;
import com.dayaokeji.rhythmschoolstudent.utils.GroupUtils;
import com.dayaokeji.rhythmschoolstudent.utils.InputUtils;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.GroupApi;
import com.dayaokeji.server_api.domain.CreateGroup;
import com.dayaokeji.server_api.domain.Group;
import com.dayaokeji.server_api.domain.UserInfo;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;


/**
 * 创建群组
 */
public class CreateEditGroupActivity extends BaseActivity {

    private static final int CHOOSE_MEMBER_REQUEST_CODE = 10001;

    public static final String EXTRA_IS_EDIT = "is_edit";
    public static final String EXTRA_GROUP_ENTITY = "group_entity";

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_group_name)
    EditText etGroupName;
    @BindView(R.id.et_group_desc)
    EditText etGroupDesc;
    @BindView(R.id.tv_join_member)
    TextView tvJoinMember;
    @BindView(R.id.tv_group_permission)
    TextView tvGroupPermission;
    @BindView(R.id.ll_choose_member)
    LinearLayout llChooseMember;

    private Set<UserInfo> participantsArrayList;
    private static final GroupApi groupApi = ApiUtils.getApi(GroupApi.class);
    private Call<ServerResponse<Void>> createCall;
    private boolean isEdit;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_edit_group);
        setSupportActionBar(toolbar);

        isEdit = getIntent().getBooleanExtra(EXTRA_IS_EDIT, false);

        init();
    }

    private void init() {
        setOnListener();
        if (isEdit){
            initUpdate();
        }
    }

    private void initUpdate() {
        Group group = (Group) getIntent().getSerializableExtra(EXTRA_GROUP_ENTITY);
        if (group != null) {
            etGroupName.setText(group.getName());
//            etGroupDesc.setText(group.getRemark());
//            tvGroupPermission.setText(GroupUtils.getGroupPermissionName(group.getVisibility()));
        }
        llChooseMember.setVisibility(View.GONE);
    }

    private void setOnListener() {
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (isEdit) {
            getMenuInflater().inflate(R.menu.update_group, menu);
        }else{
            getMenuInflater().inflate(R.menu.create_group, menu);
        }
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_save_group:
                if (isEdit) {
                    updateValidate();
                }else{
                    createValidate();
                }
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @OnClick({
            R.id.ll_choose_group_permission,
            R.id.ll_choose_member
    })
    public void onClick(View view) {
        AndroidUtils.hideSoftInput(getWindow());
        switch (view.getId()) {
            case R.id.ll_choose_group_permission:
                chooseGroupPermission();
                break;
            case R.id.ll_choose_member:
                Intent intent = new Intent(CreateEditGroupActivity.this, ChooseParticipantsActivity.class);
                intent.putExtra(ChooseParticipantsActivity.EXTRA_CHOOSER_PARTICIPANTS, (Serializable) participantsArrayList);
                startActivityForResult(intent,CHOOSE_MEMBER_REQUEST_CODE);
                break;
        }
    }

    /**
     * 验证输入
     */
    private void createValidate() {
        if (InputUtils.validateInput(etGroupName, R.string.please_input_group_name) &&
                InputUtils.validateInput(etGroupDesc,R.string.please_input_group_desc) &&
                InputUtils.validateInput(tvGroupPermission,R.string.please_choose_group_permission) &&
                InputUtils.validateInput(tvJoinMember,R.string.please_choose_group_member)) {
            if (participantsArrayList != null && participantsArrayList.size() > 0) {
                create();
            }else{
                ToastUtils.info("请选择群组人员");
            }
        }
    }

    /**
     * 验证输入
     */
    private void updateValidate() {
        if (InputUtils.validateInput(etGroupName, R.string.please_input_group_name) &&
                InputUtils.validateInput(etGroupDesc,R.string.please_input_group_desc) &&
                InputUtils.validateInput(tvGroupPermission,R.string.please_choose_group_permission) &&
                InputUtils.validateInput(tvJoinMember,R.string.please_choose_group_member)) {
            update();
        }
    }

    /**
     * 创建群组
     */
    private void create() {
        CreateGroup createGroup = new CreateGroup();
        createGroup.setName(etGroupName.getText().toString().trim());
        createGroup.setRemark(etGroupDesc.getText().toString().trim());
        createGroup.setCreateTime(DateUtils.format(System.currentTimeMillis(),DateUtils.FORMAT_DATE));
        createGroup.setCreatorId(UserUtils.getUserInfo().getId());
        createGroup.setGroupUserList(getUserIds());
        createCall = groupApi.create(createGroup);
        createCall.enqueue(new ServerCallback<Void>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    ToastUtils.info(getString(R.string.create_success));
                    EventBus.getDefault().post(new UpdateGroupEvent());
                }
            }
        });
    }

    /**
     * 更新群组
     */
    private void update() {
        CreateGroup createGroup = new CreateGroup();
        createGroup.setName(etGroupName.getText().toString().trim());
        createGroup.setRemark(etGroupDesc.getText().toString().trim());
        createGroup.setCreateTime(DateUtils.format(System.currentTimeMillis(),DateUtils.FORMAT_DATE));
        createGroup.setCreatorId(UserUtils.getUserInfo().getId());
        createCall = groupApi.update(createGroup);
        createCall.enqueue(new ServerCallback<Void>() {
            @Override
            public void onResponse(boolean success, ServerResponse<Void> response) {
                if (success) {
                    ToastUtils.info(getString(R.string.create_success));
                    EventBus.getDefault().post(new UpdateGroupEvent());
                }
            }
        });
    }

    /**
     * 选择群组权限dialog
     */
    private void chooseGroupPermission() {
        final List<GroupPermission> permissionList = new ArrayList<>();
        permissionList.add(new GroupPermission(1, "私有"));
        permissionList.add(new GroupPermission(2, "成员可见"));
        permissionList.add(new GroupPermission(3, "公开"));
        final OptionsPickerView optionsPickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int i, int i1, int i2, View view) {
                GroupPermission groupPermission = permissionList.get(i);
                if (groupPermission != null) {
                    if (tvGroupPermission != null) {
                        tvGroupPermission.setText(groupPermission.getName());
                        tvGroupPermission.setTag(groupPermission.getCode());
                    }
                }
            }
        })
                .setTitleText("选择群组权限")
                .build();
        optionsPickerView.setPicker(permissionList);
        optionsPickerView.show();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case CHOOSE_MEMBER_REQUEST_CODE:
                    participantsArrayList = ((Set<UserInfo>) data.getSerializableExtra(ChooseParticipantsActivity.EXTRA_CHOOSER_PARTICIPANTS));
                    tvJoinMember.setText("已选择"+String.valueOf(participantsArrayList == null? 0 : participantsArrayList.size())+"人");
                    break;
            }
        }
    }

    /**
     * 得到用户id
     * @return
     */
    private List<Integer> getUserIds() {
        List<Integer> userIds = new ArrayList<>();
        if (participantsArrayList != null) {
            for (UserInfo userInfo : participantsArrayList) {
                userIds.add(Integer.valueOf(userInfo.getId()));
            }

            return userIds;
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        if (createCall != null) {
            createCall.cancel();
        }
        super.onDestroy();
    }
}
